package com.lzs.system.modules.${moduleName}.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzs.common.dto.PageQuery;
<#if inOut>
import com.lzs.common.exception.LzsBusinessException;
</#if>
import com.lzs.common.utils.valid.BeanValidator;
import com.lzs.common.utils.valid.NumberValidator;
<#if oneToManyTableDto.open>
import com.lzs.system.modules.${moduleName}.dao.${oneToManyTableDto.j_oinTable}JoinDao;
import com.lzs.common.pojo.${moduleName}.${oneToManyTableDto.j_oinTable}Join;
</#if>
import com.lzs.system.modules.${moduleName}.dto.*;
import com.lzs.system.modules.${moduleName}.service.${t_ableName}Service;
import com.lzs.common.vo.CommonResult;
<#if inOut>
import com.lzs.common.vo.SelectVo;
import com.lzs.common.utils.easy.EasyExcelUtils;
</#if>
import com.lzs.system.modules.${moduleName}.dao.${t_ableName}Dao;
import com.lzs.common.pojo.${moduleName}.${t_ableName};
<#list tableFieldList as tableField>
    <#if tableField.joinDict!="">
import com.lzs.common.service.SysDictDetailService;
    <#break >
    </#if>
</#list>
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
<#if inOut>
import org.springframework.web.multipart.MultipartFile;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
</#if>
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ${t_ableName}ServiceImpl extends ServiceImpl<${t_ableName}Dao,${t_ableName}> implements ${t_ableName}Service {

    <#if oneToManyTableDto.open>
        @Autowired
        private ${oneToManyTableDto.j_oinTable}JoinDao ${oneToManyTableDto.joinTable}JoinDao;
    </#if>
    <#list tableFieldList as tableField>
        <#if tableField.joinDict!="">
        @Autowired
        private SysDictDetailService sysDictDetailService;
        <#break >
        </#if>
    </#list>

    @Override
    public CommonResult<${t_ableName}> getByPage(PageQuery pageQuery,${t_ableName}GetByPageDto dto){
        baseMapper.getByPage(pageQuery.toPage(), dto);
        return pageQuery.toCommonResult();
    }

    @Override
    public CommonResult<${t_ableName}> getById(String id){
        ${t_ableName} ${tableName} = baseMapper.selectById(id);
        return CommonResult.OK(${tableName});
    }

    @Override
    public CommonResult updateById(${t_ableName}UpdateByIdDto dto){
        BeanValidator.check(dto,${t_ableName}UpdateByIdDto.class);
        ${t_ableName} ${tableName} = new ${t_ableName}();
        BeanUtils.copyProperties(dto,${tableName});
        int updateRow = baseMapper.updateById(${tableName});
        NumberValidator.checkIsNotOne(updateRow,"修改失败");
        return CommonResult.OK();
    }

    @Override
    public CommonResult deleteById(String id){
        int deleteRow = baseMapper.deleteById(id);
        NumberValidator.checkIsNotOne(deleteRow,"删除失败");
        return CommonResult.OK();
    }

    @Override
    public CommonResult deleteFlagById(String id){
        Integer deleteFlagRow = baseMapper.deleteFlagById(id);
        NumberValidator.checkIsNotOne(deleteFlagRow,"禁用失败");
        return CommonResult.OK();
    }

    @Override
    public CommonResult save(${t_ableName}SaveDto dto){
        BeanValidator.check(dto,${t_ableName}UpdateByIdDto.class);
        ${t_ableName} ${tableName} = new ${t_ableName}();
        BeanUtils.copyProperties(dto,${tableName});
        Integer insertRow = baseMapper.insert(${tableName});
        NumberValidator.checkIsNotOne(insertRow,"添加失败");
        return CommonResult.OK();
    }

<#if oneToManyTableDto.open>
    @Override
    public CommonResult get${oneToManyTableDto.j_oinTable}By${oneToManyTableDto.j_oinField}Page(PageQuery pageQuery
    ,Get${oneToManyTableDto.j_oinTable}By${oneToManyTableDto.j_oinField}PageDto dto){
        ${oneToManyTableDto.joinTable}JoinDao.selectPage(pageQuery.toPage(), Wrappers.<${oneToManyTableDto.j_oinTable}Join>lambdaQuery()
    .select()
    .eq(${oneToManyTableDto.j_oinTable}Join::get${oneToManyTableDto.j_oinTableField},dto.get${oneToManyTableDto.j_oinTableField}())
    <#list oneToManyTableDto.whereFieldList as whereField>
        <#if whereField.fieldSearchType=="EQ" || whereField.fieldSearchType=="SELECT">
            .eq(
        </#if>
        <#if whereField.fieldSearchType=="LIKE">
            .like(
        </#if>
        <#if whereField.fieldSearchType=="NE">
            .ne(
        </#if>
        <#if whereField.fieldSearchType=="GT">
            .gt(
        </#if>
        <#if whereField.fieldSearchType=="LT">
            .lt(
        </#if>
        <#if whereField.fieldSearchType=="GE">
            .ge(
        </#if>
        <#if whereField.fieldSearchType=="LE">
            .le(
        </#if>
        <#if whereField.jdbcType=="VARCHAR">
            StringUtils.isNotBlank
        <#else >
            Objects.nonNull
        </#if>
            (dto.get${whereField.columnNameTitleCase}()),${oneToManyTableDto.j_oinTable}Join::get${whereField.columnNameTitleCase},dto.get${whereField.columnNameTitleCase}())

    </#list>
    );
        return pageQuery.toCommonResult();
    }

    @Override
    public CommonResult<${oneToManyTableDto.j_oinTable}Join> get${oneToManyTableDto.j_oinTable}ById(String id){
    ${oneToManyTableDto.j_oinTable}Join ${oneToManyTableDto.joinTable}Join = ${oneToManyTableDto.joinTable}JoinDao.selectById(id);
        return CommonResult.OK(${oneToManyTableDto.joinTable}Join);
    }

    @Override
    public CommonResult update${oneToManyTableDto.j_oinTable}ById(${oneToManyTableDto.j_oinTable}UpdateByIdJoinDto dto){
        BeanValidator.check(dto,${oneToManyTableDto.j_oinTable}UpdateByIdJoinDto.class);
        ${oneToManyTableDto.j_oinTable}Join ${oneToManyTableDto.joinTable}Join = new ${oneToManyTableDto.j_oinTable}Join();
        BeanUtils.copyProperties(dto,${oneToManyTableDto.joinTable}Join);
        int updateRow = ${oneToManyTableDto.joinTable}JoinDao.updateById(${oneToManyTableDto.joinTable}Join);
        NumberValidator.checkIsNotOne(updateRow,"修改失败");
        return CommonResult.OK();
    }

    @Override
    public CommonResult delete${oneToManyTableDto.j_oinTable}ById(String id){
        int deleteRow = ${oneToManyTableDto.joinTable}JoinDao.deleteById(id);
        NumberValidator.checkIsNotOne(deleteRow,"删除失败");
        return CommonResult.OK();
    }

    @Override
    public CommonResult save${oneToManyTableDto.j_oinTable}(${oneToManyTableDto.j_oinTable}SaveJoinDto dto){
    BeanValidator.check(dto,${oneToManyTableDto.j_oinTable}UpdateByIdJoinDto.class);
        ${oneToManyTableDto.j_oinTable}Join ${oneToManyTableDto.joinTable}Join = new ${oneToManyTableDto.j_oinTable}Join();
        BeanUtils.copyProperties(dto,${oneToManyTableDto.joinTable}Join);
        Integer insertRow = ${oneToManyTableDto.joinTable}JoinDao.insert(${oneToManyTableDto.joinTable}Join);
        NumberValidator.checkIsNotOne(insertRow,"添加失败");
        return CommonResult.OK();
    }
</#if>
<#if inOut>

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult importExcel(MultipartFile multipartFile) {
        List<${t_ableName}ExcelDto> importDtoList = null;
            try {
                importDtoList = EasyExcelUtils.importExcel(multipartFile, ${t_ableName}ExcelDto.class);
            } catch (IOException e) {
                log.error(e.getMessage(),e);
                throw new LzsBusinessException("解析excel失败");
            }
        <#list tableFieldList as tableField>
            <#if tableField.joinDict!="" && tableField.inOut>
        List<SelectVo> selectVoList = sysDictDetailService.listByDictLabel("${tableField.joinDict}");
                <#break >
            </#if>
        </#list>

        for (int i = 0; i < importDtoList.size(); i++) {
            ${t_ableName}ExcelDto ${tableName}ExcelDto = importDtoList.get(i);
            try {
                BeanValidator.check(${tableName}ExcelDto);
            }catch (Exception e){
                <#--存在图片-->
                <#list tableFieldList as tableField>
                    <#if tableField.fieldInputType=="IMAGE_UPLOAD" && tableField.inOut>
                //删除导入的图片
                this.delFile(importDtoList);
                    <#break >
                    </#if>
                </#list>
                log.error(e.getMessage(),e);
                throw new LzsBusinessException("添加第["+(i+1)+"]条数据校验失败:"+e.getMessage());
            }
            <#--存在与字典关联关系-->
            <#list tableFieldList as tableField>
                <#if tableField.joinDict!="" && tableField.inOut>
            String ${tableField.columnName}Str = ${tableName}ExcelDto.get${tableField.columnNameTitleCase}Str();
            int finalI = i;
            SelectVo selectVo = selectVoList.stream()
                .filter(s -> s.getLabel().equals(${tableField.columnName}Str))
                .findFirst()
                .orElseThrow(()->{
                    return new LzsBusinessException("第["+(finalI +1)+"]条数据["+${tableField.columnName}Str+"]格式不正确");
            });
            ${tableName}ExcelDto.set${tableField.columnNameTitleCase}(selectVo.getValue());
                <#break >
                </#if>
            </#list>

            try {
                ${t_ableName} ${tableName} = new ${t_ableName}();
                BeanUtils.copyProperties(${tableName}ExcelDto,${tableName});
                <#--存在图片-->
                <#list tableFieldList as tableField>
                    <#if tableField.fieldInputType=="IMAGE_UPLOAD" && tableField.inOut>
                String ${tableField.columnName} = ${tableName}.get${tableField.columnNameTitleCase}();
                ${tableField.columnName} = ${tableField.columnName}.replace(PropertiesUtils.getExcelUploadImgSaveToLocalUrlVal(),PropertiesUtils.getExcelServerPrefixLocalVal());
                ${tableName}.set${tableField.columnNameTitleCase}(${tableField.columnName});
                    </#if>
                </#list>

                int insert = baseMapper.insert(${tableName});
                if (NumberValidator.checkIsNotOne(insert)) {
                <#--存在图片-->
                <#list tableFieldList as tableField>
                    <#if tableField.fieldInputType=="IMAGE_UPLOAD" && tableField.inOut>
                //删除导入的图片
                this.delFile(importDtoList);
                        <#break >
                    </#if>
                </#list>
                    throw new LzsBusinessException("添加第["+(i+1)+"]条数据失败");
                }
            }catch (Exception e){
                <#--存在图片-->
                <#list tableFieldList as tableField>
                    <#if tableField.fieldInputType=="IMAGE_UPLOAD" && tableField.inOut>
                //删除导入的图片
                this.delFile(importDtoList);
                        <#break >
                    </#if>
                </#list>
                log.error(e.getMessage(),e);
                throw new LzsBusinessException("添加第["+(i+1)+"]条数据失败");
            }

        }
        return CommonResult.OK(importDtoList.size());
    }

    private void delFile(List<${t_ableName}ExcelDto> importDtoList){
        //删除导入的图片
        for (${t_ableName}ExcelDto importDto : importDtoList) {
            <#--存在图片-->
            <#list tableFieldList as tableField>
                <#if tableField.fieldInputType=="IMAGE_UPLOAD" && tableField.inOut>
            if (Objects.nonNull(importDto)&&StringUtils.isNotBlank(importDto.get${tableField.columnNameTitleCase}())) {
                new File(importDto.get${tableField.columnNameTitleCase}()).delete();
            }
                    <#break >
                </#if>
            </#list>

        }
    }

    @Override
    public void exportExcel(${t_ableName}GetByPageDto dto, HttpServletResponse response) {

        List<${t_ableName}ExcelDto> ${tableName}List = baseMapper.getExportExcelData(dto);
        <#list tableFieldList as tableField>
            <#if tableField.joinDict!="" && tableField.inOut>
        List<SelectVo> selectVoList = sysDictDetailService.listByDictLabel("${tableField.joinDict}");
            <#break >
            </#if>
        </#list>

        for (${t_ableName}ExcelDto ${tableName}ExcelDto : ${tableName}List) {
            <#list tableFieldList as tableField>
                <#if tableField.joinDict!="" && tableField.inOut>
            String ${tableField.columnName} = ${tableName}ExcelDto.get${tableField.columnNameTitleCase}();
            SelectVo selectVo = selectVoList.stream()
                .filter(s -> s.getValue().equals(${tableField.columnName}))
                .findFirst()
                .orElseGet(()->{
                    SelectVo selectVo1 = new SelectVo();
                    selectVo1.setLabel(${tableField.columnName});
                    return selectVo1;
            });
            ${tableName}ExcelDto.set${tableField.columnNameTitleCase}Str(selectVo.getLabel());
                    <#break >
                </#if>
            </#list>


        }
        EasyExcelUtils.exportExcel(${tableName}List,${t_ableName}ExcelDto.class,response);
    }

</#if>
}
